import numpy as np
import cv2


def gaussian_filter(img, K=3, mul=0, sigma=0.8):
    H, W, C = img.shape
    pad = K // 2
    out = np.zeros((H + pad * 2, W + pad * 2, C), dtype=float)
    out[pad: pad + H, pad: pad + W] = img.astype(float)
    G = np.zeros((K, K), dtype=float)

    # 生成卷积核
    for i in range(-pad, -pad + K):
        for j in range(-pad, -pad + K):
            G[j + pad, i + pad] = np.exp(-((i - mul) ** 2 + (j - mul) ** 2) / (2 * sigma ** 2))
    G /= (2 * np.pi * sigma ** 2)
    G /= G.sum()

    tmp = out.copy()
    for i in range(H):
        for j in range(W):
            for k in range(C):
                out[pad + i, pad + j, k] = np.sum(G * tmp[i: i + K, j: j + K, k])
    out = np.clip(out, 0, 255)
    out = out[pad: pad + H, pad: pad + W].astype(np.uint8)

    cv2.imshow('a', out)
    cv2.imshow('b', img)
    cv2.waitKey(0)
    return out


if __name__ == '__main__':
    img = cv2.imread('../data/1586550081897406465/42.png')
    rlt = gaussian_filter(img)

